package com.chrissy.music.framework.exception;

import com.alibaba.fastjson2.JSON;
import com.chrissy.music.common.constant.HttpStatus;
import com.chrissy.music.common.exception.ApiException;
import com.chrissy.music.common.result.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

/**
 * @author Johnson
 */
@Slf4j
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = "请求访问：" + request.getRequestURI() + "，认证失败，无法访问系统资源";
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(JSON.toJSONString(Result.error(code, msg)));
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new ApiException(500, e.getMessage());
        }
    }
}